﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Web.Api.Server.Models;

namespace Web.Api.Server.ViewModels.Shops
{
    public class CartsPostViewModel : IValidatableObject
    {
        public int? Id { get; set; }

        [Required]
        public int GoodsId { get; set; }

        [Required]
        [Range(1, 9999)]
        public int Number { get; set; }

        [Required]
        public decimal Price { get; set; }

        [Required]
        public int ShopId { get; set; }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            var db = validationContext.GetService(typeof(ApplicationDbContext)) as ApplicationDbContext;
            var goods = db.GoodsSet
                .Where(g => g.Id == GoodsId && g.ShopId == ShopId)
                .First();
            if (goods == null)
            {
                yield return new ValidationResult("商品不存在.", new[] { nameof(GoodsId) });
            }
        }
    }
}
